package com.example.client_anna.module.branch_home;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.example.client_anna.R;
import com.example.client_anna.base.BaseActivity;
import com.example.client_anna.network.room.dao.GoodsDao;
import com.example.client_anna.network.room.database.ClientDataBase;
import com.example.client_anna.network.room.entity.Goods;
import com.example.client_anna.util.entity.HomeShopGroupItem;
import com.example.client_anna.network.okhttp3.HttpUtilImpl;
import com.example.client_anna.network.okhttp3.RequestUrl;
import com.example.client_anna.util.tool.LocalThreadPools;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.kunminx.linkage.LinkageRecyclerView;
import com.kunminx.linkage.adapter.viewholder.LinkagePrimaryViewHolder;
import com.kunminx.linkage.adapter.viewholder.LinkageSecondaryFooterViewHolder;
import com.kunminx.linkage.adapter.viewholder.LinkageSecondaryHeaderViewHolder;
import com.kunminx.linkage.adapter.viewholder.LinkageSecondaryViewHolder;
import com.kunminx.linkage.bean.BaseGroupedItem;
import com.kunminx.linkage.contract.ILinkagePrimaryAdapterConfig;
import com.kunminx.linkage.contract.ILinkageSecondaryAdapterConfig;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutorService;

import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * @author cy
 * @email 272884043@qq.com
 * @date 2021/10/19
 */
public class HomeDetailsActivity extends BaseActivity{

    private static final String TAG = "HomeDetailsActivity";
    private static final int SPAN_COUNT_FOR_GRID_MODE = 2;
    private static final int MARQUEE_REPEAT_LOOP_MODE = -1;
    private static final int MARQUEE_REPEAT_NONE_MODE = 0;

    //传值
    public static final String HOME_BID = "bid";
    public static final String HOME_THEME = "theme";
    public static final String HOME_DISTRIBUTION = "distribution";
    public static final String HOME_STAR = "star";
    public static final String HOME_SALE = "sale";
    public static final String HOME_START = "start";
    public static final String HOME_MINUS = "minus";
    public static final String HOME_NOTICE = "notice";
    public static final String HOME_IMAGE = "image";
    public static final String HOME_DETAIL_IMAGE = "detail_image";

    //接收
    private static String bid;
    private static String theme;
    private static String distribution;
    private static String star;
    private static String sale;
    private static String start;
    private static String minus;
    private static String notice;
    private static String image;
    private static String detail_image;

    private static String minus_reduce;

    //控件
    private Toolbar home_toolbar;
    private TextView home_theme_text;
    private TextView home_distribution_text;
    private TextView home_star_text;
    private TextView home_sale_text;
    private TextView home_start_text;
    private TextView home_minus_text;
    private TextView home_notice_text;
    private ImageView home_image;
    private ImageView home_image_bg;

    private static GoodsDao dao;
    private static List<Goods> goodsList;

    private ImageView home_shop_box;
    private ImageView home_shop_box_bg;
    private ImageView home_shop_submit;
    private TextView goods_price_sum;
    private TextView goods_price_sum_del;
    private TextView goods_num;

    private Float sum = 0.0f;
    private int single_num;
    private static int whole_num;

    private static RecyclerView bottomRecyclerView;
    private static ShopGoodsBottomAdapter shopGoodsBottomAdapter;

    //上一次点击删除按钮的时候过后的时间，要大于300ms，才能再次执行删除操作
    //系统删除动画的执行时间默认为250ms
    private static boolean isDeleteAble = true;
    //是否执行了购物车删除操作
    private static boolean isDeleteItem = false;
    //数据库是否产生变动
    private static boolean isItemDataChange = false;
    //购物车产生数据变动的item的位置
    private static int goods_position;

    private static final int DATA_INIT = 0;
    private static final int RECYCLERVIEW_CHANGE = 1;
    private static final int BOTTOM_RECYCLERVIEW_CHANGE = 2;
    //数据库数据变化，通知UI界面进行更新
    private static int isBaseDataUiChange = DATA_INIT;

    private PopupWindow popupWindow;
    private LinkageRecyclerView recyclerView;

    //清空购物车
    private LinearLayout goods_clear;
    private static boolean isClearData = false;

    //线程池
    private static ExecutorService executorService = LocalThreadPools.getExecutorService();

    private static boolean isShowBottom = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home_details);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            //5.0 全透明实现
            //getWindow.setStatusBarColor(Color.TRANSPARENT)
            //View.SYSTEM_UI_FLAG_FULLSCREEN：Activity全屏显示，且状态栏被隐藏覆盖掉
            //View.SYSTEM_UI_FLAG_LAYOUT_STABLE这个标志来帮助你的应用维持一个稳定的布局
            Window window = getWindow();
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.setStatusBarColor(Color.TRANSPARENT);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //4.4 全透明状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        //获取UI展示界面传递过来的值
        getIntentInfo();
        //初始化GoodsViewMode
        loadGoodsViewMode();
        //加载控件实例
        loadInstance();
        //显示数据
        initSetData();

        setSupportActionBar(home_toolbar);
        //系统自带导航栏
        ActionBar actionBar = getSupportActionBar();
        if(actionBar!=null){
            //系统自带的返回按钮
            actionBar.setDisplayHomeAsUpEnabled(true);
            //按钮图片
            actionBar.setHomeAsUpIndicator(R.drawable.details_back);
        }

        Home_Details_Okhttp3();

        //点击底部弹出购物车
        //点击提按钮进行订单的提交
        loadOnclick();
    }

    /*--------------------------------点击底部弹出购物车和进入订单确认页面------------------------------*/
    private void loadOnclick() {
        ImageView submit = (ImageView) findViewById(R.id.home_shop_submit);
        RelativeLayout bottom = (RelativeLayout) findViewById(R.id.home_shop_bottom);

        //屏幕高度
        Point point =new Point();
        getWindowManager().getDefaultDisplay().getRealSize(point);
        int screen_y = point.y;

        int bottom_y = bottom.getLayoutParams().height;

        Log.d(TAG,"height y"+String.valueOf(screen_y));

        //点击提按钮进行订单的提交
        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(sum<Float.valueOf(start)||sum==0.0){
                    Toast.makeText(HomeDetailsActivity.this,"还不到起送价格或者购买的商品数量还不足一件",Toast.LENGTH_SHORT).show();
                }else {
                    //进入确认购买页面
                    submitGoodsInfo();
                }
            }
        });

        //点击底部弹出购物车页面
        bottom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //总价不为0表示有选择商品
                if(sum!=0){
                    if(isShowBottom==true) {
                        //偏移的高度
                        int height = screen_y - bottom.getBottom() + bottom_y;
                        goodsBottomInfo(height);
                        isShowBottom = false;
                    }else {
                        popupWindow.dismiss();
                        isShowBottom = true;
                    }
                }else {
                    Toast.makeText(HomeDetailsActivity.this, "选择的购买商品数量不足一件", Toast.LENGTH_SHORT).show();
                }

            }
        });

    }

    //携带参数跳转到订单确认页面
    private void submitGoodsInfo(){
        Intent intent = new Intent(HomeDetailsActivity.this, HomeOrderActivity.class);
        //商家id,店铺名,所需的配送费
        intent.putExtra("bid",bid);
        intent.putExtra("b_name",theme);
        intent.putExtra("b_distribution",distribution);
        intent.putExtra("b_full",minus_reduce);
        startActivity(intent);
    }

    /*-------------------------------------底部弹窗，购物车信息--------------------------------------*/
    //购物车信息
    private void goodsBottomInfo(int height){
        View view = getLayoutInflater().inflate(R.layout.home_shop_bottom,null);
        View rootView = getLayoutInflater().inflate(R.layout.activity_home_details,null);

        bottomRecyclerView = (RecyclerView) view.findViewById(R.id.bottom_goods_recyclerView);
        //GridLayoutManager布局方式，参数1:Context，参数2:列数
        GridLayoutManager layoutManager = new GridLayoutManager(HomeDetailsActivity.this, 1);
        //加载布局方式
        bottomRecyclerView.setLayoutManager(layoutManager);
        bottomRecyclerView.setFocusable(true);
        //加载适配器
        Message message = new Message();
        message.what = 1;
        handler.sendMessage(message);

        popupWindow = new PopupWindow(this);

        //初始化的时候通过购物车中的item数量进行显示的最大高度判断
        if(goodsList.size()<=5){
            popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
            popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        }else {
            bottomRecyclerView.setPadding(0,0,0,height);
            popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
            popupWindow.setHeight(HomeDetailsActivity.this.getResources().getDisplayMetrics().heightPixels/4*2);
        }

        //需要显示的布局
        popupWindow.setContentView(view);
        //背景透明
        popupWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));

        //设置popupWindow不需要获得焦点
        popupWindow.setFocusable(false);
        popupWindow.setOutsideTouchable(true);
        //系统动画效果
        popupWindow.setAnimationStyle(android.R.style.Animation_Dialog);
        //参数：需要显示在哪和活动的rootView布局，底部，x偏移值，y偏移值
        //计算偏移值的时候，x,y对应的是控件的左上角
        popupWindow.showAtLocation(rootView,Gravity.BOTTOM,0,height);

        goods_clear = (LinearLayout) view.findViewById(R.id.bottom_goods_clear);
        goods_clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(HomeDetailsActivity.this);
                final AlertDialog dialog = builder.create();
                View dialogView = View.inflate(HomeDetailsActivity.this,R.layout.home_shop_bottom_alertdialog,null);
                dialog.setView(dialogView);

                //消除AlertDialog的底层背景
                Window window = dialog.getWindow();
                window.setBackgroundDrawable(new BitmapDrawable());
                dialog.show();

                //显示的宽和高
                dialog.getWindow().setLayout(HomeDetailsActivity.this.getResources().getDisplayMetrics().widthPixels/5*4,
                        LinearLayout.LayoutParams.WRAP_CONTENT);

                ImageView cancel_top = (ImageView) dialogView.findViewById(R.id.bottom_alert_cancel);
                FrameLayout cancel = (FrameLayout) dialogView.findViewById(R.id.bottom_alert_cancel_but);
                FrameLayout clear = (FrameLayout) dialogView.findViewById(R.id.bottom_alert_clear_but);

                //是否清空购物车，右上角按钮
                cancel_top.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });

                //是否清空购物车，取消按钮
                cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });

                //清空购物车
                clear.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //清空购物车，根据商家id
                        executorService.execute(new Runnable() {
                            @Override
                            public void run() {
                                List<Goods> all_goods = dao.queryGoodsByBid(bid);
                                for(Goods i:all_goods){
                                    dao.deleteGoods(i);
                                }
                                isClearData = true;
                            }
                        });
                        dialog.dismiss();
                    }
                });

            }
        });

    }

    /*--------------------------观察者模式，观察的对象SQLite中的表Goods--------------------------------*/
    //ViewMode数据提供
    private void loadGoodsViewMode() {
        dao = ClientDataBase.getDataBase(this).getGoodsDao();
        //商品总价
        goods_price_sum = (TextView) findViewById(R.id.home_shop_sum);
        goods_price_sum_del = (TextView) findViewById(R.id.home_shop_sum_del);
        goods_price_sum_del.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);//添加中划线
        goods_num = (TextView) findViewById(R.id.home_shop_box_top);
        home_shop_submit = (ImageView) findViewById(R.id.home_shop_submit);
        home_shop_box = (ImageView) findViewById(R.id.home_shop_box);
        home_shop_box_bg = (ImageView) findViewById(R.id.home_shop_box_top_bg);

        GoodsViewModel goodsViewModel = new ViewModelProvider(this,
                ViewModelProvider.AndroidViewModelFactory.getInstance(getApplication()))
                .get(GoodsViewModel.class);

        //刷新数据，数据库数据变动的时候不需要新开线程就可以直接进行刷新数据的操作
        goodsViewModel.getListGoods().observe(this, new Observer<List<Goods>>() {
            @Override
            public void onChanged(List<Goods> goods) {
                Log.d(TAG,"bid "+bid);
                //根据商家id从本地数据库中筛选出该购物车展示的信息
                List<Goods> list = new ArrayList<>();
                for(Goods i:goods){
                    if(i.bid.equals(bid)){
                        list.add(i);
                    }else {
                        //结束单次循环
                        continue;
                    }
                }
                //用户购买该商家商品的信息
                goodsList = list;

                Log.d(TAG,"size"+String.valueOf(goodsList.size()));

                if (goodsList != null) {

                    //商品总价
                    sum = 0.0f;
                    //单个商品的数量
                    single_num = 0;
                    for(Goods i:goodsList){
                        Log.d(TAG,"goods price "+i.food_price);
                        single_num = i.food_amount;
                        //加入购物车的商品数量
                        whole_num = whole_num+i.food_amount;
                        sum=sum+(i.food_price*single_num);
                    }

                    //餐盒的颜色和数量提示
                    if(whole_num!=0){
                        home_shop_box.setBackgroundResource(R.drawable.home_shop_box_chose);
                        home_shop_box_bg.setVisibility(View.VISIBLE);
                        goods_num.setVisibility(View.VISIBLE);
                        goods_num.setText(String.valueOf(whole_num));
                    }else {
                        home_shop_box.setBackgroundResource(R.drawable.home_shop_box_none);
                        home_shop_box_bg.setVisibility(View.INVISIBLE);
                        goods_num.setVisibility(View.INVISIBLE);
                    }

                    //起送价格
                    if(sum>=Float.valueOf(start)){
                        home_shop_submit.setBackgroundResource(R.drawable.home_shop_but_radius_chose);
                    }else {
                        home_shop_submit.setBackgroundResource(R.drawable.home_shop_but_radius_none);
                    }

                    whole_num = 0;
                    goods_price_sum_del.setText(String.valueOf(sum));

                    Float end_sum = sum;
//                            +Float.valueOf(distribution);//加配送费
                    
                    //满减
                    if(!("".equals(minus))) {
                        HashMap<String, String> map = new HashMap<>();
                        Gson gson = new Gson();
                        map = gson.fromJson(minus, new TypeToken<HashMap<String, String>>() {
                        }.getType());
                        Set set = map.keySet();
                        //具体减多少
                        Float reduce = 0.0f;
                        for (Iterator iterator = set.iterator(); iterator.hasNext(); ) {
                            String key = String.valueOf(iterator.next());
                            if (Float.valueOf(key) <= sum) {
                                String value = String.valueOf(map.get(key));
                                reduce = reduce + Float.valueOf(value);
                            }

                        }
                        //显示总价，满减
                        DecimalFormat decimalFormat = new DecimalFormat(".00");//保留俩位小数
                        goods_price_sum.setText(decimalFormat.format(end_sum-reduce));
                        minus_reduce = String.valueOf(reduce);
                    }else {
                        //显示总价，没有达到满减
                        DecimalFormat decimalFormat = new DecimalFormat(".00");
                        goods_price_sum.setText(decimalFormat.format(end_sum));
                        minus_reduce = "0";
                    }

                    //数据库产生变化的时候，如果在购物车点击了减号，当被点击的item减后为0，触发以下代码
                    //通知适配器数据改变，执行动画，删除该item
                    if(isDeleteItem==true){

                        if(isDeleteAble) {
                            isDeleteAble = false;
                            shopGoodsBottomAdapter.notifyItemRemoved(goods_position);
                            //执行.notifyDataSetChanged()方法会回调onBindViewHolder()
                            shopGoodsBottomAdapter.notifyItemRangeChanged(goods_position,shopGoodsBottomAdapter.getItemCount());
                            //当购物车为空的时候关闭底部弹窗
                            if (goodsList.size() == 0 || goodsList == null) {
                                popupWindow.dismiss();
                            }else if(goodsList.size()<=5){
                                bottomRecyclerView.setPadding(0,0,0,0);
                                popupWindow.update(ViewGroup.LayoutParams.MATCH_PARENT,
                                        bottomRecyclerView.getHeight());
                            }
                            //执行删除动画会有250ms的时间，在这之间再次点击会引起闪退
                            //设置全局变量isDeleteAble为true时能执行删除
                            try {
                                Thread.sleep(300);
                                isDeleteAble = true;
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            isDeleteItem = false;

                        }
                    }
                    
                    //购物车数据改变，商品展示页面刷新
                    if(isItemDataChange==true){
                        recyclerView.getSecondaryAdapter().notifyDataSetChanged();
                        isItemDataChange = false;
                    }

                    //清空购物车
                    if(isClearData==true){
                        shopGoodsBottomAdapter.notifyDataSetChanged();
                        recyclerView.getSecondaryAdapter().notifyDataSetChanged();
                        popupWindow.dismiss();
                        isClearData = false;
                    }

                    //UI界面更新
                    switch (isBaseDataUiChange){
                        case RECYCLERVIEW_CHANGE:
                            recyclerView.getSecondaryAdapter().notifyDataSetChanged();
                            isBaseDataUiChange = 0;
                            break;
                        case BOTTOM_RECYCLERVIEW_CHANGE:
                            shopGoodsBottomAdapter.dataChange();
                            shopGoodsBottomAdapter.notifyDataSetChanged();
                            isBaseDataUiChange = 0;
                            break;
                        case DATA_INIT:
                            break;
                    }

                }
            }
        });
    }

    //获取传递过来的商家信息
    private void getIntentInfo(){
        Intent intent = getIntent();
        bid = intent.getStringExtra(HOME_BID);
        theme = intent.getStringExtra(HOME_THEME);
        distribution = intent.getStringExtra(HOME_DISTRIBUTION);
        star = intent.getStringExtra(HOME_STAR);
        sale = intent.getStringExtra(HOME_SALE);
        start = intent.getStringExtra(HOME_START);
        minus = intent.getStringExtra(HOME_MINUS);
        notice = intent.getStringExtra(HOME_NOTICE);
        image = intent.getStringExtra(HOME_IMAGE);
        detail_image = intent.getStringExtra(HOME_DETAIL_IMAGE);
    }

    //实例的初始化
    private void loadInstance(){
        home_toolbar = (Toolbar) findViewById(R.id.home_toolbar);
        home_theme_text = (TextView) findViewById(R.id.home_details_theme);
        home_distribution_text = (TextView) findViewById(R.id.home_details_distribution);
        home_star_text = (TextView) findViewById(R.id.home_details_star);
        home_sale_text = (TextView) findViewById(R.id.home_details_sale);
        home_start_text = (TextView) findViewById(R.id.home_box_start);
        home_minus_text = (TextView) findViewById(R.id.home_details_minus);
        home_notice_text = (TextView) findViewById(R.id.home_details_notice);
        home_image = (ImageView) findViewById(R.id.home_details_image);
        home_image_bg = (ImageView) findViewById(R.id.home_details_image_bg);
    }

    //初始化商家信息
    private void initSetData() {
        home_theme_text.setText(theme);
        loadDistribution();
        home_star_text.setText(star);
        home_sale_text.setText(sale);
        home_start_text.setText("￥"+start+"起送");
        //满减
        if(!("".equals(minus))) {
            home_minus_text.setText(getFullMinus(minus));
        }else {
            home_minus_text.setText("该商家还没有活动");
        }
        home_notice_text.setText("公告：" + notice);
        //加载图片进home_image_bg
        Glide.with(this)
                .load(RequestUrl.getUrl()+detail_image)
                .placeholder(R.drawable.explore_placeholder)
                .error(R.drawable.explore_error)
                .dontAnimate()
                .into(home_image_bg);

        //加载图片进home_image
        Glide.with(this)
                .load(RequestUrl.getUrl()+image)
                .placeholder(R.drawable.explore_placeholder)
                .error(R.drawable.explore_error)
                .dontAnimate()
                .into(home_image);
    }

    //将json形式的字符串转成需要样式
    private String getFullMinus(String fullminus){
        HashMap<String,String> map = new HashMap<>();
        Gson gson = new Gson();
        map = gson.fromJson(fullminus,new TypeToken<HashMap<String,String>>(){}.getType());
        String toString = "\"";
        Set set = map.keySet();
        for (Iterator iterator = set.iterator(); iterator.hasNext();){

            //iterator.hasNext()只是判断下一个元素的有无，并不移动指针
            //iterator.next()向下移动指针
            String key = String.valueOf(iterator.next());
            String value = String.valueOf(map.get(key));

            if (iterator.hasNext()){
                toString = toString+key+"减"+value+" | ";
            }else {
                toString = toString+key+"减"+value;
            }
        }
        return toString+"\"";
    }

    private void loadDistribution(){
        Float dis = Float.valueOf(distribution);
        //判断是否为0，免配送费
        if(Math.abs(dis)<0.001){
            home_distribution_text.setText("免配送费");
        }else {
            //不为0，如果小数点后为0，则取整
            if(dis.intValue()-dis==0.0){
                home_distribution_text.setText(String.valueOf("配送费￥"+dis.intValue()));
            }else {
               home_distribution_text.setText("配送费￥"+dis.toString());
            }
        }
    }

    /*-------------------------------------获取商家商品信息------------------------------------------*/
    //商家商品数据请求
    private void Home_Details_Okhttp3() {
        //具体请求对象
        String info = "business_info";
        //链接的地址
        String address = RequestUrl.getUrl()+"home"+"?"+"request="+info;
        //创建RequestBody请求体,用于数据的提交
        RequestBody requestBody = new FormBody.Builder()
                .add("bid",bid)
                .build();
        HttpUtilImpl.sendOKHttpRequest(address, requestBody, new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //onFailure方法用于网络请求失败后执行的语句
                //取消请求的判断，true用户主动关闭活动页面，false超时或者网络出错
                if(e.toString().contains("closed")){
                    //用户直接关闭页面后取消请求
                    call.cancel();
                }else{
                    //网络不稳定，或者无网络
                    Message message = new Message();
                    message.what = 400;
                    handler.sendMessage(message);
                    //取消请求
                    call.cancel();
                }
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //onResponse方法用于接收访成功后回调后的操作
                //得到response对象的具体内容
                String responseData=response.body().string();
                //分析返回的数据
                ParesJsonWithGSON(responseData);
            }
        });

    }

    //json数据处理
    private List<HomeShopGroupItem> items;
    private void ParesJsonWithGSON(String jsonData){
        if(!(jsonData.isEmpty())){

            Gson gson = new Gson();
            Boolean msg = false;
            JSONObject jsonObject = new JSONObject();
            jsonObject = JSON.parseObject(jsonData);

            switch (jsonObject.get("message").toString()){
                case "success":
                    Log.d(TAG,"shop info Start receiving");
                    items = gson.fromJson(jsonObject.get("data").toString(),new TypeToken<List<HomeShopGroupItem>>(){}.getType());
                    Log.d(TAG,"shop info "+jsonObject.get("data"));
                    msg = true;
                    break;
                case "fail":
                    msg = false;
            }

            if(msg==true) {
                Message message = new Message();
                message.what = 200;
                handler.sendMessage(message);
            }else {
                Message message = new Message();
                message.what = 201;
                handler.sendMessage(message);
            }

        }

    }

    /*-------------------------------商家商品信息的显示初始化-----------------------------------------*/
    //recyclerView初始化
    private void initRecyclerView() {
        recyclerView = (LinkageRecyclerView) findViewById(R.id.home_shop_linkage);
        recyclerView.init(items, new ShopPrimaryAdapterConfig(),new ShopSecondaryAdapterConfig());
    }

    //左侧布局适配器
    private static class ShopPrimaryAdapterConfig implements ILinkagePrimaryAdapterConfig{

        private Context mContext;

        @Override
        public void setContext(Context context) {
            mContext =context;
        }

        //左侧布局
        @Override
        public int getLayoutId() {
            return R.layout.home_shop_recyclerview_primary;
        }

        //分组具体控件id
        @Override
        public int getGroupTitleViewId() {
            return R.id.primary_group_text;
        }

        //布局id
        @Override
        public int getRootViewId() {
            return R.id.primary_layout_group;
        }

        @Override
        public void onBindViewHolder(LinkagePrimaryViewHolder holder, boolean b, String title) {
            TextView textView = ((TextView) holder.getGroupTitle());

            textView.setText(title);

            textView.setBackgroundColor(mContext.getResources().getColor(
                    b ? R.color.shop_primary_background_chose : R.color.shop_primary_background_none
            ));

            textView.setTextColor(ContextCompat.getColor(mContext,
                    b ? R.color.shop_primary_text_chose : R.color.shop_primary_text_none
            ));

            textView.setEllipsize(b ? TextUtils.TruncateAt.MARQUEE : TextUtils.TruncateAt.END);

            textView.setFocusable(b);
            textView.setFocusableInTouchMode(b);
            textView.setMarqueeRepeatLimit(b ? MARQUEE_REPEAT_LOOP_MODE : MARQUEE_REPEAT_NONE_MODE);

        }
        //左侧点击事件
        @Override
        public void onItemClick(LinkagePrimaryViewHolder holder, View view, String title) {

        }

    }

    //右侧布局适配器
    private static class ShopSecondaryAdapterConfig implements
            ILinkageSecondaryAdapterConfig<HomeShopGroupItem.ItemInfo>{

        private Context mContext;

        @Override
        public void setContext(Context context) {
            mContext = context;
        }

        @Override
        public int getGridLayoutId() {
            return 0;
        }

        //右侧布局
        @Override
        public int getLinearLayoutId() {
            return R.layout.home_shop_recyclerview_secondary;
        }

        //右侧分组标签
        @Override
        public int getHeaderLayoutId() {
            return R.layout.adapter_home_shop_header;
        }

        //尾部标签
        @Override
        public int getFooterLayoutId() {
            return R.layout.adapter_home_shop_footer;
        }

        //头标签具体控件id
        @Override
        public int getHeaderTextViewId() {
            return R.id.home_secondary_header;
        }

        @Override
        public int getSpanCountOfGridMode() {
            return SPAN_COUNT_FOR_GRID_MODE;
        }

        @Override
        public void onBindViewHolder(LinkageSecondaryViewHolder holder, BaseGroupedItem<HomeShopGroupItem.ItemInfo> item) {

            ((TextView) holder.getView(R.id.shop_goods_title)).setText(item.info.getTitle());
            ((TextView) holder.getView(R.id.shop_goods_comment)).setText(item.info.getComment());
            ((TextView) holder.getView(R.id.shop_goods_detail)).setText(item.info.getDescription());
            ((TextView) holder.getView(R.id.shop_goods_sales)).setText(item.info.getSales().toString());
            ((TextView) holder.getView(R.id.shop_goods_price)).setText(item.info.getPrice().toString());
            Glide.with(mContext)
                    .load(RequestUrl.getUrl()+item.info.getImage())
                    .into((ImageView) holder.getView(R.id.shop_goods_img));

            ImageView reduce = (ImageView) holder.getView(R.id.shop_goods_reduce);
            TextView amount_text = (TextView) holder.getView(R.id.shop_goods_text);

            //是否显示减号和数量：初始化的时候通过fid判断该item是否存在于数据库中
            Boolean isShow = false;

            //点击购物车，改变item的数量的时候，数据库会产生变动
            //goodsViewModel会观察到，对goodsList对象进行更新，然后执行适配器的.notifyDataSetChanged()方法
            //执行会回调onBindViewHolder()
            for (Goods i:goodsList){
                if (i.food_id.equals(item.info.getFid())){
                    isShow = true;
                    amount_text.setText(i.food_amount.toString());
                    break;
                }else {
                    isShow = false;
                }
            }

            if (isShow==true){
                reduce.setVisibility(View.VISIBLE);
                amount_text.setVisibility(View.VISIBLE);
            }else {
                reduce.setVisibility(View.INVISIBLE);
                amount_text.setVisibility(View.INVISIBLE);
            }

            //点击加号事件
            holder.getView(R.id.shop_goods_add).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    isShowBottom = true;
                    if(reduce.getVisibility()==View.INVISIBLE && amount_text.getVisibility()==View.INVISIBLE){
                        reduce.setVisibility(View.VISIBLE);
                        amount_text.setVisibility(View.VISIBLE);
                    }

                    executorService.execute(new Runnable() {
                        @Override
                        public void run() {

                            //使用item的fid去进行查询看商品是否已被用户添加进购物车
                            Goods isFid = dao.queryGoodsByFid(item.info.getFid());

                            if(isFid==null){
                                //通知UI线程进行更新
                                isBaseDataUiChange = 1;
                                //添加商品信息进数据库
                                Goods newFid = new Goods(
                                        bid,
                                        item.info.getFid(),
                                        item.info.getTitle(),
                                        item.info.getImage(),
                                        item.info.getPrice(),
                                        1
                                );
                                dao.insertGoods(newFid);
                            }else {
                                //通知UI线程进行更新
                                isBaseDataUiChange = 1;
                                isFid.food_amount++;
                                dao.updateGoods(isFid);
                            }
                        }
                    });

                }
            });

            //点击减号事件
            holder.getView(R.id.shop_goods_reduce).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    isShowBottom = true;
                    executorService.execute(new Runnable() {
                        @Override
                        public void run() {
                            //使用item的fid去进行查询看商品是否已被用户添加进购物车
                            Goods isFid = dao.queryGoodsByFid(item.info.getFid());

                            //已经在数据库中
                            if(isFid!=null){
                                //对点击的item做出反应，如果减1后为0则删除数据库中的该条信息
                                //不为0就对数据库中该item信息做减1操作
                                int amount = isFid.food_amount;
                                if(--amount<=0){
                                    //为0隐藏减号和数量
                                    isBaseDataUiChange = 1;
                                    isFid.food_amount=isFid.food_amount-1;
                                    dao.deleteGoods(isFid);

                                }else {
                                    //通知UI线程进行更新
                                    isBaseDataUiChange = 1;
                                    isFid.food_amount=isFid.food_amount-1;
                                    dao.updateGoods(isFid);
                                }
                            }
                        }
                    });

                }
            });
        }

        @Override
        public void onBindHeaderViewHolder(LinkageSecondaryHeaderViewHolder holder, BaseGroupedItem<HomeShopGroupItem.ItemInfo> item) {
            //设置右侧分组标签
            ((TextView) holder.getView(R.id.home_secondary_header)).setText(item.header);
        }

        @Override
        public void onBindFooterViewHolder(LinkageSecondaryFooterViewHolder holder, BaseGroupedItem<HomeShopGroupItem.ItemInfo> item) {

        }
    }

    /*-------------------------------------购物车信息适配器------------------------------------------*/
    //购物车适配器
    private static class ShopGoodsBottomAdapter extends RecyclerView.Adapter<ShopGoodsBottomAdapter.ViewHolder>{
        private Context mContext;
        private List<Goods> mGoods;

        //viewHolder与xml布局中的控件关联
        static class ViewHolder extends RecyclerView.ViewHolder{
            ImageView img;
            TextView name;
            TextView price;
            TextView amount;

            ImageView add;
            ImageView reduce;
            public ViewHolder(View view){
                super(view);
                img = (ImageView) view.findViewById(R.id.bottom_goods_rec_img);
                name = (TextView) view.findViewById(R.id.bottom_goods_rec_name);
                price = (TextView) view.findViewById(R.id.bottom_goods_rec_price);
                amount = (TextView) view.findViewById(R.id.bottom_goods_rec_amount);

                add = (ImageView) view.findViewById(R.id.bottom_goods_rec_price_add);
                reduce = (ImageView) view.findViewById(R.id.bottom_goods_rec__reduce);
            }
        }

        public ShopGoodsBottomAdapter(List<Goods> goods){
            mGoods = goods;
        }

        public void dataChange(){
            mGoods = goodsList;
        }

        @NonNull
        @NotNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull @NotNull ViewGroup viewGroup, int viewType) {
            if (mContext == null){
                mContext = viewGroup.getContext();
            }
            View view = LayoutInflater.from(mContext).inflate(R.layout.home_shop_bottom_recyclerview,viewGroup,false);
            ViewHolder holder = new ViewHolder(view);

            holder.add.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int position = holder.getAdapterPosition();
                    Goods goods = mGoods.get(position);
                    executorService.execute(new Runnable() {
                        @Override
                        public void run() {
                            Goods box_goods = dao.queryGoodsByFid(goods.food_id);
                            if(box_goods!=null){
                                //通知ui更新
                                isBaseDataUiChange = 2;
                                //通知对item的删除
                                isItemDataChange = true;
                                box_goods.food_amount++;
                                dao.updateGoods(box_goods);
                            }
                        }
                    });
                }
            });

            holder.reduce.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int position = holder.getAdapterPosition();
                    Goods goods = mGoods.get(position);
                    executorService.execute(new Runnable() {
                        @Override
                        public void run() {
                            Goods box_goods = dao.queryGoodsByFid(goods.food_id);
                            if(box_goods!=null){
                                int amount = box_goods.food_amount;
                                if(--amount<=0){
                                    box_goods.food_amount--;
                                    isDeleteItem = true;
                                    goods_position = position;
                                    mGoods.remove(position);
                                    isItemDataChange = true;
                                    //先对全局变量进行赋值再进行数据库的变动
                                    dao.deleteGoods(box_goods);
                                }else {
                                    box_goods.food_amount--;
                                    isItemDataChange = true;
                                    //通知ui更新
                                    isBaseDataUiChange = 2;
                                    dao.updateGoods(box_goods);
                                }
                            }
                        }
                    });
                }
            });

            return holder;
        }

        @Override
        public void onBindViewHolder(@NonNull @NotNull ShopGoodsBottomAdapter.ViewHolder viewHolder, int position) {
            Goods goods = mGoods.get(position);
            viewHolder.name.setText(goods.food_name);
            viewHolder.price.setText(goods.food_price.toString());

            viewHolder.amount.setText(goods.food_amount.toString());

            String url = RequestUrl.getUrl()+goods.food_image;
            displayImageCenter(mContext,viewHolder.img,url);

            viewHolder.add.setVisibility(View.VISIBLE);
            viewHolder.reduce.setVisibility(View.VISIBLE);
            viewHolder.amount.setVisibility(View.VISIBLE);
        }

        public static void displayImageCenter(Context context,final ImageView imageView,String url){
            RequestOptions options = new RequestOptions()
                    //磁盘缓存
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    //内存缓存，默认false，表示不跳过内存缓存
                    .skipMemoryCache(false)
                    //加载错误显示的图片
                    .error(R.drawable.explore_error)
                    //占位图
                    .placeholder(R.drawable.explore_placeholder)
                    //设置图片的宽和高，获取imageView控件的宽度和高
                    //注：在onCreate中是获取不到imageview的高度的，因为这个时候imageView控件自己都还没有测量
                    .override(imageView.getMeasuredWidth(), imageView.getMeasuredHeight())
                    //不需要动画效果，默认300
                    .dontAnimate();
            //Glide缓存顺序：内存>磁盘>网络
            Glide.with(context)
                    .asBitmap()
                    .load(url)
                    .apply(options)
                    .into(imageView);
        }

        @Override
        public int getItemCount() {
            return mGoods.size();
        }

        @Override
        public long getItemId(int position) {
            return position;
        }
    }

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what){
                case 400:
                    //请求服务器数据失败
                    Toast.makeText(HomeDetailsActivity.this,"服务器异常，请等待！",Toast.LENGTH_SHORT).show();
                    break;
                case 200:
                    initRecyclerView();
                    break;
                case 201:
                    Toast.makeText(HomeDetailsActivity.this,"该商家还没有添加商品信息",Toast.LENGTH_SHORT).show();
                    break;
                case 1:
                    shopGoodsBottomAdapter = new ShopGoodsBottomAdapter(goodsList);
                    //加载闪烁问题：添加标记tag,tag标记着每一张请求url的图片，加载的时候防止重新加载
                    //需要重写adapter的getItemId方法
                    shopGoodsBottomAdapter.setHasStableIds(true);
                    //recyclerView布局加载适配器
                    bottomRecyclerView.setAdapter(shopGoodsBottomAdapter);
                    break;
            }
        }
    };

    //返回按钮点击事件，返回上一个活动
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){
            case android.R.id.home:
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        isShowBottom = true;
        //该活动关闭，关闭线程池
        LocalThreadPools.ShutdownLocalThreadPools();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        isShowBottom = true;
    }

}